package it.fuesi.synoutils.services.tasks.search;

import android.util.Log;

import it.fuesi.synoutils.adapters.EmuleSearchAdapter;
import it.fuesi.synoutils.constants.ApiErrorCode;
import it.fuesi.synoutils.model.base.ErrorObject;
import it.fuesi.synoutils.model.emulesearch.EmuleSearchClientParameters;
import it.fuesi.synoutils.model.emulesearch.EmuleSearchResultsDataObject;
import it.fuesi.synoutils.model.emulesearch.EmuleSearchResultsResponse;
import it.fuesi.synoutils.model.emulesearch.EmuleSearchStartResponse;
import it.fuesi.synoutils.services.client.EmuleSearchClient;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class EmuleSearchTask extends BaseTask<EmuleSearchResultsResponse, EmuleSearchResultsDataObject, EmuleSearchClientParameters> {

    private static final String TAG = EmuleSearchTask.class.getName();

    public EmuleSearchTask(EmuleSearchAdapter adapter){
        super(adapter);
    }


    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public EmuleSearchResultsResponse run(EmuleSearchClientParameters params)  throws Exception {
            EmuleSearchClient client = ServiceClientFactory.getClient(EmuleSearchClient.class);

            final int searchId;


            if(!params.isStarted()){
                Log.d(TAG, "Starting search --> ");
                publishProgress("Starting search...");
                EmuleSearchStartResponse startResponse = client.start(params.getKey(),"generalsearch", 1, 0, 0);
                if(startResponse.isSuccess())
                    searchId = startResponse.getSearchid();
                else{
                    searchId = -1;
                    //TODO: manage start error
                }
            }else
                searchId = params.getSearchid();


            publishProgress("Querying emule search engines " + params.getCounter());
            EmuleSearchResultsResponse resp = client.list(searchId, "result_enum","SOURCE","DESC",0,100);
            resp.setSearchid(searchId);
            if(!resp.isSuccess()){
                resp.setSuccess(true);
                resp.setError(new ErrorObject());
                resp.getError().setCode(ApiErrorCode.retry.getErrorCode());
            }else{
                EmuleSearchResultsDataObject data = new EmuleSearchResultsDataObject();
                data.setItems(resp.getItems());
                resp.setData(data);
            }

            return resp;

    }

    @Override
    protected void onPostExecute(EmuleSearchResultsResponse response) {
        EmuleSearchAdapter adapter = (EmuleSearchAdapter)getAdapter();
        adapter.setFinished(response.isSearchdone());
        adapter.setSearchid(response.getSearchid());

        super.onPostExecute(response);


    }
}
